/*
* 错误收集
* */
//onerror=handleErr
//
//function handleErr(msg,url,l)
//{
//    var txt='';
//    txt="There was an error on this pages.\n\n"
//    txt+="Error: " + msg + "\n"
//    txt+="URL: " + url + "\n"
//    txt+="Line: " + l + "\n\n"
//    txt+="Click OK to continue.\n\n"
//    //alert(txt)
//    console.error(txt);
//    return false
//}
//
// 判断浏览器设备

//  是否显示其他信息
function letShow() {
    var flag = validateNull();
    if (flag) {
        $('#qidian_input').prop('disabled', false);
        $('.takeman').removeClass('hide');
        var type = $('.header-tabs .airport-selected').data('type');
        if (type == "dropOff") { // 送机才会有值机业务
            $('.vip-passageway').removeClass('hide');
        }
        $('.costBox').removeClass('hide');
        $('.pay-types').removeClass('hide');
        $('.btn-call').removeClass('btn-call-disabled').addClass('btn-call-abled');
    } else {
        $('.takeman').addClass('hide');
        $('.vip-passageway').addClass('hide');
        $('.costBox').addClass('hide');
        $('.pay-types').addClass('hide');
        $('.btn-call').addClass('btn-call-disabled').removeClass('btn-call-abled');
    }
}

// 验证输入起始点
function validateNull() {
    var qidain = $('#qidian_input').data();
    var zhongdian = $('#zhongdian_input').data();
    console.log(qidain, zhongdian);
    if (!!qidain.name && !!zhongdian.name) {
        return true;
    } else {
        return false;
    }
}

window.browser = {
    versions: function () {
        var u = window.navigator.userAgent;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
            iPad: u.indexOf('iPad') > -1, //是否为iPad
            webApp: u.indexOf('Safari') == -1,//是否为web应用程序，没有头部与底部
            weixin: u.indexOf('MicroMessenger') == -1 //是否为微信浏览器
        };
    }()
}

window.isH5 = !getLocalStorage("isH5") ? false : true;

// pushState 实现浏览器返回监听
function pushHistory(title, url) {
    var state = {
        title: title,
        url: url
    };
    window.history.pushState(state, title, url);
}

// 手机号码校验
function checkPhone(phone) {
    var flag = true;
    flag = /^1(2|3|4|5|6|7|8|9)\d{9}$/.test(phone);
    return flag;
}

// 手机号码校验
function checkFlight(phone) {
    var flag = true;
    flag = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6}$/.test(phone);
    return flag;
}

//去除数组中重复对象
function arrayUnique(array) {
    var unique = {};
    array.forEach(function (a) {
        unique[JSON.stringify(a)] = 1;
    });
    array = Object.keys(unique).map(function (u) {
        return JSON.parse(u);
    });
    return array;
}

// 获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

// 计算距离和时间
function calculate(yueajax) {
    var startLocation = "", endLocation = "";
    if (!!$('#qidian_input').data('name')) {
        startLocation = getLocalStorage(START_LOCATION_INFO, 'object');
    }
    if (!!$('#zhongdian_input').data('name')) {
        endLocation = getLocalStorage(END_LOCATION_INFO, 'object');
    }
    if (startLocation === "" || endLocation === "") {
        console.log(startLocation, endLocation);
        return;
    }
    // 起始点经纬度
    var slng, slat, elng, elat;
    // 标识是否可计算
    var flag = true;
    var position = startLocation.location;// 用户可能不输入起点位置（location），以定位（position）为准
    // 起点信息
    if (position != undefined) {
        slng = position.lng;
        slat = position.lat;
    } else {
        flag = false;
    }
    // 终点信息
    position = endLocation.location;
    if (position != undefined) {
        elng = position.lng;
        elat = position.lat;
    } else {
        flag = false;
    }
    // 是否可计算距离时间等
    if (flag) {
        var promise = getRouteInfo(slng, slat, elng, elat);
        promise.then(function () {
            // 重新计算价格
            var passengerUuid = $('#passengerUuid').val();
            var $trigger = $('#carTypeText');
            var carId = $trigger.data("id");
            // alert(carId)
            valuation(passengerUuid, carId, yueajax);

        });
    }
}

// 获取路线信息
function getRouteInfo(slng, slat, elng, elat) {
    var ok = false;
    var promise = new Promise(function (resolve) {
        //构造路线导航类
        var driving = new AMap.Driving();
        // 根据起终点经纬度规划驾车导航路线
        driving.search(new AMap.LngLat(slng, slat), new AMap.LngLat(elng, elat), function (status, result) {
            setLocalStorage('routeInfo', result.routes[0]);
            ok = true;
            resolve(ok);
        });
    });
    return promise;
}

function getTimeStempDefault0() {
    var timeVal = $("#valueTo").val();
    var type = '0', hours = "", minutes;
    if (timeVal != "") {
        var timeList = timeVal.split(':');
        type = timeList[0];
        hours = +timeList[1];
        minutes = +timeList[2];
    }
    if (type == '0') {
        return '0';
    }
    var departTime = setDate(type, hours, minutes);
    return departTime.getTime();
}

// 获取时间戳
//现在默认叫即时单，到时候通过选择的时间判断叫预约单或者即时单
function getTimeStemp() {
    var timeVal = $("#valueTo").val();
    var type = '0', hours = "", minutes;
    if (timeVal != "") {
        var timeList = timeVal.split(':');
        type = timeList[0];
        hours = +timeList[1];
        minutes = +timeList[2];
    }
    var departTime = setDate(type, hours, minutes);
    return departTime.getTime();
}

function setDate(type, hours, minutes) {
    var curDate = new Date();
    var date;
    switch (type) {
        case "2":
            date = curDate.getDate() + 1;
            break;
        case "3":
            date = curDate.getDate() + 2;
            break;
        default:
            date = curDate.getDate();
            break;
    }
    curDate.setHours(hours);
    curDate.setMinutes(minutes);
    curDate.setDate(date);
    return curDate;
}

//根据不同订单状态跳转页面
function changeUrl(subStstus, orderUuid) {
    // return ;
    var orderUuid = orderUuid || "";
    var urlObj = {
        "index": function () {
            if (isH5) {
                return "/yue/h5/index";
            } else if (getLocalStorage('isTaxi') == "true") {
                return "/yue/index/taxi";
            }
            return "/yue/index";
        },
        "ratedialog": function () {
            return "/yue/ratedialog?orderUuid=" + orderUuid
        },
        100: function () {
            return "/yue/wreply?orderUuid=" + orderUuid;
        },//乘客发单、等待应答
        200: function () {
            return "/yue/wmeeting?orderUuid=" + orderUuid;
        },//司机接单中
        210: function () {
            return "/yue/wmeeting?orderUuid=" + orderUuid;
        },//司机出发、去接乘客
        220: function () {
            return "/yue/wtakecar?orderUuid=" + orderUuid;
        },//司机到达、等待乘客
        300: function () {
            return "/yue/onway?orderUuid=" + orderUuid;
        },//乘客上车、行程开始
        400: function () {
            return "/yue/onway?orderUuid=" + orderUuid;
        },//司机送达目的地
        500: function () {
            return "/yue/wpay?orderUuid=" + orderUuid;
        }, //司机确认费用
        511: function () {
            return "/yue/cancelPay?orderUuid=" + orderUuid;
        },//乘客取消，待支付取消费用
        521: function () {
            return "/yue/wpay?orderUuid=" + orderUuid;
        },//司机取消，待支付取消费用
        512: function () {
            return "/yue/wpay?orderUuid=" + orderUuid;
        },//乘客取消，待支付取消费用
        513: function () {
            return "/yue/wpay?orderUuid=" + orderUuid;
        },//乘客取消，待支付取消费用
        522: function () {
            return "/yue/wpay?orderUuid=" + orderUuid;
        },//司机取消，待支付取消费用
        523: function () {
            return "/yue/wpay?orderUuid=" + orderUuid;
        },//司机取消，待支付取消费用
        600: function () {
            return "/yue/wrated?orderUuid=" + orderUuid;
        }, //司机确认费用
        610: function () {
            return "/yue/wrated?orderUuid=" + orderUuid;
        }, //司机确认费用
        "cancelMsg": function () {
            return "/yue/cancel?orderUuid=" + orderUuid;
        }, //支付成功，进入待评价页面
        "cancelNoPay": function () {
            return "/yue/cancelNoPay?orderUuid=" + orderUuid;
        },//订单取消无取消费
        "cancelConfirmNoPay": function () {
            return "/yue/cancelConfirmNoPay?orderUuid=" + orderUuid;
        },//订单取消无取消费，确认页面
        90200: function () {
            return urlObj.cancelNoPay()
        },
        90210: function () {
            return urlObj.cancelNoPay()
        },
        90220: function () {
            return urlObj.cancelNoPay()
        },
        91200: function () {
            return urlObj.cancelNoPay()
        },
        91210: function () {
            return urlObj.cancelNoPay()
        },
        91220: function () {
            return urlObj.cancelNoPay()
        },
        "cancelYesPay": function () {
            return "/yue/cancel_success?orderUuid=" + orderUuid;
        },//订单取消,有取消费
        90511: function () {
            return urlObj.cancelYesPay();
        },
        90512: function () {
            return urlObj.cancelYesPay();
        },
        90513: function () {
            return urlObj.cancelYesPay();
        },
        91521: function () {
            return urlObj.cancelYesPay();
        },
        91522: function () {
            return urlObj.cancelYesPay();
        },
        91523: function () {
            return urlObj.cancelYesPay();
        },
        'order_list': function () {
            return "/yue/order_list";
        },
        'cancelConfirmYesPay': function () {
            return "/yue/cancelConfirmYesPay?orderUuid=" + orderUuid;
        },//有取消费用，确认页面
        990: function () {
            if (orderUuid.indexOf("&flag=false") > -1) {
                return urlObj.cancelNoPay();
            }
            return urlObj['index']();
        },
        900: function () {
            // alert("无司机接受订单，订单已自动取消！");
            return "/yue/cancel_success";
        }, //支付成功，进入待评价页面
    }
    //判断订单状态是否异常，不存在
    var urls;
    try {
        urls = urlObj[subStstus]();
    } catch (e) {
        urls = urlObj['index']();
    }

    if (!!urls) {
        //排除当前页面的跳转，不执行href。
        if (urls.indexOf(window.location.pathname) == -1) {
            window.location.replace(base + urls)
        }
    } else {
        changeUrl('index')
    }
}

//url 操作对象
var url = {
    /*
     * 功能描述：获得指定name的值
     * return 字符串/value
     * */
    getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return "";
    },
    /*
     * 功能描述：获得json参数值
     * data:{
     * name:value
     * }
     * return k;
     * k:{
     * name:value
     * }
     * */
    getUrlPara: function (data) {
        for (var i in data) {
            data[i] = this.getQueryString(i);
        }
        return data;
    },
    getAllPara: function () {
        var s = window.location.search;
        if (!s) return '';
        s = s.substr(1);
        s = decodeURI(s)
        var k = {};
        if (s.indexOf('&') == -1) {
            var arr1 = s.split('=');
            k[arr1[0]] = arr1[1];
            return k;
        }
        var arr2 = s.split('&');
        for (var i in arr2) {
            var ds = arr2[i].split('=');
            k[ds[0]] = ds[1];
        }
        return k;
    },
    /*
     * 功能描述：修改/添加url 参数值
     * data{
     * name:value
     * }
     * */
    setUrlPara: function (data) {
        var para = "";
        for (var k in data) {
            data[k] = (typeof data[k] == "string") ? (data[k]) : ('');
            para += (k + "=" + data[k] + "&");
        }

        para = para.substring(0, (para.length) - 1);
        window.location.search = para;
    },
};
//扩展Date输出格式
Date.prototype.format = function (format) {
    var date = {
        "M+": this.getMonth() + 1,
        "D+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

//根据车型调用预估接口
function valuation(passengerUuid, carId, yun) {
    if (getLocalStorage('isTaxi') == 'true') {
        return;
    }

    var routeInfo = getLocalStorage('routeInfo', 'object');
    var planTrip = routeInfo.distance / 1000;//预估里程(公里)
    var planTime = Math.ceil(routeInfo.time / 60);//预估时长(分钟)
    var departTime = getTimeStempDefault0();//非预约单传0
    var startLocation = getLocalStorage(START_LOCATION_INFO, 'object');
    var adcode = startLocation.adcode;
    //预估价请求
    var tran = +$('[name="transfervalue"]:checked').val() || ''
    window.diu = '99000740047928'
    $('.btn-call-abled').removeClass('btn-call-abled').addClass('btn-call-disabled')
    // layer.msg(levelUuid)
    yun.ajax_md5({
        planTrip: planTrip,//*预估里程(公里)
        planTime: planTime,//*预估时长(分钟)
        departTime: departTime,//*出发时间
        adCode: adcode,//*区域编码
        // diu:browser.versions.android?'imei':'idfv',// 设备唯一标识
    }, "/api/v1/passenger/express/order/valuation", function (data) {

        setLocalStorage(estimate, data.data);
        $("#moneyText").html((data.data.actPaid).toFixed(1));
        if (!!data.data.couponMoney) {
            $("#actPaid").show();
            $("#actPaid").find('span').html((data.data.couponMoney).toFixed(1));
        } else {
            $("#actPaid").hide();
        }
        $('.btn-call-disabled').removeClass('btn-call-disabled').addClass('btn-call-abled')
    }, function (data) {
        delLocalStorage(estimate)
        layer.msg(data.msg)
        // $("#actPaid").hide();
        // $("#moneyText").html(0);
    })
    // $.post("/wx/Order/specialOrder/valuation", {
    //     passengerUuid: passengerUuid, planTrip: planTrip, planTime: planTime,
    //     departTime: departTime, levelUuid: levelUuid, adCode: adcode
    // }, function (result) {
    //     //赋值预估信息
    //     if (result.success) {
    //         $("#moneyText").html(result.data.totalFare);
    //     } else {
    //         $("#moneyText").html(0);
    //     }
    // });
}

//封号提醒
function noConferred(data) {
    layer.confirm(data.msg, {
        btn: ['联系客服', '我知道了']
    }, function () {
        window.location.href = "tel:4001160592";
    }, function () {
        layer.msg('我知道了')
    });
}

/*
* yun封装Ajax请求
* 传入APPID
* 使用案例：
*  var yun=new yueajax( openId);
*  yun.ajax()//正常ajax请求
*  yun.ajax_md5()//签名加密后的请求
* */
(function (window, appid, key) {
    var yun = {};
    //为了避免多次请求validateOpenId，获取token。加入validateOpenId判断是否再次请求
    yun.ajax = function (openId, validateOpenId) {
        this.init.apply(this, arguments);
    };
    yun.ajax.prototype = {
        //初始化请求，查找是否进行中的订单，有就跳转对应面对，并同时处理
        init: function () {
            var t = this;
            t.openId = arguments[0] || getLocalStorage('openId') || '';
            t.appid = appid;
            t.key = key;
            t.token = ''
            t.orderUuid = url.getQueryString('orderUuid');
            //t.rsa();
            //是否需要用户初始化请求
            if (arguments[1] === 'validateOpenId') {
                t.init_ajax();
            } else {
                var isH5 = getLocalStorage("isH5");
                if (!!isH5) {//H 5
                    var us = getLocalStorage("yueuserH5", "object");
                    if (!us) {
                        setLocalStorage('ifBindWxUser', "false")
                    } else {
                        setLocalStorage('ifBindWxUser', "true")
                        this.token = us['token'] || '';
                    }

                    return;
                }
                //微信
                var user = getLocalStorage('yueuser', 'object');
                if (!user) {
                    t.init_ajax();
                } else {
                    this.token = user.token
                }
            }

        },
        rsa: function () {//RSA 加密解密
            var t = this;
            //alert('ccc');
            //解密对象
            t.decrypt = new JSEncrypt();
            t.decrypt.setPrivateKey(
                'MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKra+wo/pHz6/VK0\n' +
                'wgHto5jnZ+L+bUSN7yiViWP5tvtMK7KrbyaF22ADM/3nu9PoR2rcrHuOFlJFbOBX\n' +
                'JfxnEM6e1wOUKAxT83xzFv4zUTpnCQLO1SnHcH6nnug/8hDcVTjKjvfyWw0C1G/N\n' +
                '7zs2omWiSoU1GDGHOpqpIPnrEgpZAgMBAAECgYBXonBnRlOJY3eyB1MHiCuEjxUD\n' +
                'IjtLkX2dFG5fIEORy/UR9MrTOI9YROxTDJyTya1wC3ZQ/YVHd6KrwyeRug+tBLVj\n' +
                'M/nsW8JcXpoDTSmjECIptdjoiXHR2WNfQTz0hEZZLxRzNmlgZRH1W1VC/KAS/GSC\n' +
                'jiPzPamSofFU5joxMQJBANgS9G2CdH7711AbS3beRC7hb+LAcRpnWagggX6Ie5le\n' +
                'aQm2Zus1KmZlTP2axl2Q438+NTVGPWrgfiFq9X7oj60CQQDKbQc6WPolDEw3dXFS\n' +
                '8T4krf3FB+LXUKkscn5EmwiHv+oZpa8kKLwkGqzaUSIyN3muE1mJaH8s6Or2q9gO\n' +
                'nkrdAkA9hLAI2cKXQNadnRfQQRoCivbTBV1uWgyBvLeBshQWp3WaaU9GGj33J1JT\n' +
                'RhTCIPVUjf6SK2xjGIVwuEYrGsWFAkB54/MRQFjIDEKstmxZvGhmH9sKVLhUXP6x\n' +
                'g/PijdQyIe7uKKVwyZKYzvM8ttQ3ls4PcxlcM2849LvfcxSzoL+FAkBpN3h3xQen\n' +
                'mvTuzcuF4mFHl375YLcD2zRGyPGCs88OKkyzCIEwfCOfOGMmSf49TGVaSD643n+2\n' +
                '6Tyewh91R+bz'
            )
            //加密对象
            t.encrypt = new JSEncrypt();
            t.encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0bdRCaU0XxwrN8XBRKzSYMDUFh1tcB4VdG1eRXhyl+CdJfmQGLqi4/raAK/FgCOxqlVcTX66OugrZbX/Ajz0geupn7jasdVhASyLz4OqYo21ZxWSX9lQHj/rIEqpDsfLcNSYm7dyIy6QVaSR0s3I18dG0cuc1+nojzOnU7iJxLQIDAQAB')
        },
        //初始化请求，查找是否进行中的订单，有就跳转对应面对，并同时处理
        init_ajax: function () {
            var t = this;
            t.ajax(
                {openId: t.openId || ''},
                base + "/wx/passenger/login/validateOpenId",
                function (data) {
                    var d = data.data;
                    if (!d) {
                        setLocalStorage('ifBindWxUser', false)
                        delLocalStorage('yueuser')
                        changeUrl("index")
                    } else {
                        t.token = d.passengerDto.token
                        setLocalStorage('yueuser', d.passengerDto);
                        setLocalStorage('ifBindWxUser', true)
                        $('.user-mobile').html((d.passengerDto.mobile).replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
                        )
                    }
                    if (d.orderStatus.status != 0) {
                        setLocalStorage('subStatus', d.orderStatus.subStatus)
                        changeUrl(d.orderStatus.subStatus, d.orderStatus.orderUuid + '&status=' + d.orderStatus.status);
                    }
                },
                function (data) {
                    setLocalStorage('ifBindWxUser', false)
                    delLocalStorage('yueuser')
                    //changeUrl("index")

                })
        },
        /*
        * 算法逻辑
        * @（params）传入object 、字符串序列化、object FormData这三种参数，传入的数据格式决定了return的数据格式
        *      1: 参数数据类型的标记（paramsType）：
        *           字符串：1
        *           json对象：2
        *           FormData：3
        *      2: 处理参数成字符串
        *      3:增加md5验签逻辑(时间戳)
        *      4:对加密数据进行排序之前先拼上appid和token，排序完成后最后面拼上 key
        *      5:生成签名
        *      6:拼接随机数和签名，并返回最后的数据。
        * */
        md5: function (params) {
            var t = this;
            if (params === null) return null;
            //处理参数 如果传入的是字符串 则对
            var originalParamStr;
            var resultParam = params;
            var paramsType = 0;
            var paramsTypeStr = params.toString();
            if (typeof params === 'string') paramsType = 1; //string
            if ('[object Object]' === paramsTypeStr) {
                paramsType = 2;
            }
            ; //JSON对象
            if ('[object FormData]' === paramsTypeStr) {
                paramsType = 3
            }
            ; //FormData对象
            //不可处理的参数类型报错
            if (!paramsType) return 'parameterTypeError';

            //处理参数成字符串
            switch (paramsType) {
                case 1 : {
                    originalParamStr = params;
                    break;
                }
                case 2 : {
                    originalParamStr = $.param(params);
                    break;
                }
                case 3 : {
                    var iterator = params.entries();
                    var paramFormStr = '';
                    //递归遍历
                    var recursion_iterator = function (data) {
                        if (data.done === false && !(data.value[1] instanceof File)) { //排除文件类型
                            paramFormStr += (data.value[0] + '=' + data.value[1] + '&');
                        }
                        if (data.done === false) {
                            recursion_iterator(iterator.next());
                        }
                    };
                    recursion_iterator(iterator.next());
                    if (paramFormStr.length > 0) paramFormStr = paramFormStr.substring(0, paramFormStr.length - 1);
                    originalParamStr = paramFormStr;
                    break;
                }
            }

            //1.中文解码 2.加号转换为空格
            originalParamStr = decodeURIComponent(originalParamStr).replace(/\+/g, " ");

            //增加md5验签逻辑
            var paramStr = '';
            var noncestr = new Date().getTime();

            var paramObject = {'noncestr': noncestr};
            var keyArray = ['noncestr'];
            var entryStrArray = originalParamStr.split('&');
            for (var i in entryStrArray) {
                var key = entryStrArray[i].split('=')[0];
                var value = entryStrArray[i].split('=')[1];
                if (key && value !== undefined && value !== '') {
                    keyArray.push(key);
                    paramObject[key] = value;
                }
                keyArray.sort();
            }
            for (var i in keyArray) {
                paramStr += (keyArray[i] + '=' + paramObject[keyArray[i]] + '&');
            }
            //拼上,appid,token
            paramStr = 'appid=' + t.appid + '&' + (paramStr || "") + 'token=' + t.token;

            //对加密数据进行排序
            function strToObj(str) {
                var obj;
                str = str.replace(/&/g, "','");
                str = str.replace(/=/g, "':'");
                str = "({'" + str + "'})";
                obj = eval(str);
                return obj;
            }

            paramStr = strToObj(paramStr);
            var kName = [], cParam = {};
            for (var ic in paramStr) {
                kName.push(ic);
            }
            kName.sort();
            for (var j in kName) {
                if (!!paramStr[kName[j]]) cParam[kName[j]] = paramStr[kName[j]];
            }
            window.dd = cParam;
            paramStr = decodeURIComponent($.param(cParam)).replace(/\+/g, " ");
            // 最后拼上key
            paramStr += '&key=' + t.key;
            //生成签名
            // console.log('signStr:' + paramStr);
            // console.log(paramStr,CryptoJS.MD5(paramStr).toString());
            var sign = (CryptoJS.MD5(paramStr).toString()).toLocaleUpperCase();

            //签名完成后移除key参数
            paramStr = paramStr.substring(0, paramStr.lastIndexOf('&'));
            //拼接随机数和签名
            switch (paramsType) {
                case 1 : {
                    resultParam = paramStr + ('&sign=' + sign) + ('&token=' + this.token);
                    break;
                }
                case 2 : {
                    resultParam['noncestr'] = noncestr;
                    resultParam['sign'] = sign;
                    resultParam['appid'] = t.appid;
                    resultParam['token'] = t.token;
                    break;
                }
                case 3 : {
                    resultParam.append('noncestr', noncestr);
                    resultParam.append('sign', sign);
                    resultParam.append('token', t.token);
                    resultParam.append('appid', t.appid);
                    break;
                }
            }
            return resultParam;
        },
        md52: function (params) {
            var self = this;
            var noncestr = new Date().getTime();
            var parm = '{"appid":"' + this.appid + '","noncestr":"' + noncestr + '","key":"' + this.key + '"}'
            params = JSON.stringify(params)
            console.log(params)

            var paramsStr = parm + params;
            console.log(paramsStr)
            return {
                params: params,
                noncestr: noncestr,
                sign: (CryptoJS.MD5(paramsStr).toString()).toLocaleUpperCase()
            }
        },
        //获取订单信息
        order_ajax: function (callback, errorback) {
            var t = this;
            //路径中不含有orderUuid的一律回跳至首页
            if (t.orderUuid == "undefined" || t.orderUuid == "null" || t.orderUuid == "") {
                layer.msg('没有orderUuid', function () {
                    changeUrl('index')
                })
                // window.location.href = "/yue/index";
                return;
            }
            t.ajax_md5({orderUuid: t.orderUuid}, base + '/api/v1/passenger/token/order/info', function (data) {
                $('#cancel-rule').attr('href', base + '/h5/passenger/cancelRule?appid=' + appid + '&orderUuid=' + data.data.uuid);
                callback(data);
            }, function (data) {
                layer.msg(data.msg, function () {
                    changeUrl('index')
                })
                errorback(data);
            })
        },
        //数据加密且执行请求
        ajax_md5: function (params, url, successCallBack, errorCallBack) {
            var t = this;
            // if(!t.token){layer.msg('网络延迟，请稍候请求');return ;}
            params = t.md5(params);
            if ('parameterTypeError' === params || params == false) {
                console.log('MD5签名：参数类型错误')
                return false;
            }
            this.ajax(params, url, successCallBack, errorCallBack)
        },
        //数据加密且执行请求
        ajax_md52: function (params, url, successCallBack, errorCallBack, type) {
            var t = this;
            // if(!t.token){layer.msg('网络延迟，请稍候请求');return ;}
            params = t.md52(params);
            if ('parameterTypeError' === params || params == false) {
                console.log('MD5签名：参数类型错误')
                return false;
            }
            this.ajax2(params, url, successCallBack, errorCallBack, type)
        },
        //ajax封装
        ajax: function (params, url, successCallBack, errorCallBack, type) {
            var t = this;
            var params = encryptRSA.objToRsa(params);
            var ajaxObject = {
                type: !type ? 'POST' : type,
                url: url,
                data: params,
                headers: {
                    token: t.token,
                    appid: appid,
                    sing: params.sing,
                },
                dataType: 'json',
                cache: false,
                success: function (result) {
                    result = decryptRSA.rsaToObj(result);
                    if (result.success) {
                        if (successCallBack) {
                            successCallBack(result);
                        }
                    } else {
                        if (result.errCode == 10012 && !t.errCode) {
                            t.errCode = true;
                            noConferred(result)
                            return;
                        }
                        if (result.errCode == 10011 && !t.errCode) {
                            t.errCode = true;
                            layer.msg(result.msg, function () {
                                delLocalStorage("yueuserH5")
                                setLocalStorage('ifBindWxUser', "false")
                                delLocalStorage("yueuser")
                                changeUrl('index')
                            })
                            return;
                        }
                        if (errorCallBack) {
                            errorCallBack(result);
                        }
                    }
                },
                error: function (data) {

                    var d;
                    if (data.status == 200 && isRSA) {
                        //d=t.decrypt.decryptLong(decodeURIComponent(data.responseText).replace(/[\s\n\t]+/g,''));
                        d = decryptRSA.rsaToObj(decodeURIComponent(data.responseText).replace(/[\s]+/g, ''));
                        console.log(data.responseText, d);
                        layer.msg(d.msg || '请求异常，请联系管理员');
                        return;
                    }
                    layer.msg('请求异常，请联系管理员');
                }
            };
            $.ajax(ajaxObject);
        },
        //ajax2封装
        ajax2: function (params, url, successCallBack, errorCallBack, type) {
            var t = this;
            if (!this.token) {
                var us = getLocalStorage("yueuserH5", "object")
                this.token = us.token
            }
            var params1 = encryptRSA.objToRsa(params);
            console.log(params1)
            var ajaxObject = {
                type: !type ? 'POST' : type,
                url: url,
                data: params1.params,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    noncestr: params1.noncestr,
                    token: t.token,
                    appid: t.appid,
                    sign: params1.sign,
                },
                dataType: 'json',
                cache: false,
                success: function (result) {
                    result = decryptRSA.rsaToObj(result);
                    if (result.success) {
                        if (successCallBack) {
                            successCallBack(result);
                        }
                    } else {
                        if (result.errCode == 10012 && !t.errCode) {
                            t.errCode = true;
                            noConferred(result)
                            return;
                        }
                        if (result.errCode == 10011 && !t.errCode) {
                            t.errCode = true;
                            layer.msg(result.msg, function () {
                                delLocalStorage("yueuserH5")
                                setLocalStorage('ifBindWxUser', "false")
                                delLocalStorage("yueuser")
                                changeUrl('index')
                            })
                            return;
                        }
                        if (errorCallBack) {
                            errorCallBack(result);
                        }
                    }
                },
                error: function (data) {

                    var d;
                    if (data.status == 200 && isRSA) {
                        //d=t.decrypt.decryptLong(decodeURIComponent(data.responseText).replace(/[\s\n\t]+/g,''));
                        d = decryptRSA.rsaToObj(decodeURIComponent(data.responseText).replace(/[\s]+/g, ''));
                        console.log(data.responseText, d);
                        layer.msg(d.msg || '请求异常，请联系管理员');
                        return;
                    }
                    layer.msg('请求异常，请联系管理员');
                }
            };
            $.ajax(ajaxObject);
        },
        //获取乘客当前位置并传给服务端进行计算路程和时间,传入乘客位置。
        twoPoint_ajax: function (params, successCallBack, errorCallBack) {

            var t = this, url = base + "/api/v1/passenger/token/order/getDriving";
            params.orderUuid = this.orderUuid;
            t.ajax_md5(params, url, successCallBack, errorCallBack)
        },
        //    定位请求，onComplete：定位成功回掉方法，onError：定位失败回掉方法
        position: function (onComplete, onError) {
            var t = this;
            if (!t.map) {
                t.map = new AMap.Map('container', {
                    resizeEnable: true
                });
            }
            t.map.plugin('AMap.Geolocation', function () {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, //是否使用高精度定位，默认:true
                    timeout: 10000, //超过10秒后停止定位，默认：无穷大
                    // buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    buttonPosition: 'RB'
                });
                t.map.addControl(geolocation);
                geolocation.getCurrentPosition();
                AMap.event.addListener(geolocation, 'complete', onComplete); //返回定位信息
                AMap.event.addListener(geolocation, 'error', onError); //返回定位出错信息
            });
        },
        //超时等待费用
        waitFare_ajax: function (successCallBack, errorCallBack) {
            var t = this, url = base + "/api/v1/passenger/token/order/waitFare";
            t.ajax_md5({orderUuid: t.orderUuid}, url, successCallBack, errorCallBack)
        },
        //    时间计算：明后天和上下午计算
        time_count: function (time) {
            var time = time;
            var now = new Date();
            var hour = time.getHours(), hourName = ""
            if (hour < 6) {
                hourName = "凌晨"
            } else if (hour < 9) {
                hourName = "早上"
            } else if (hour < 12) {
                hourName = "上午"
            } else if (hour < 14) {
                hourName = "中午"
            } else if (hour < 17) {
                hourName = "下午"
            } else if (hour < 19) {
                hourName = "傍晚"
            } else if (hour < 22) {
                hourName = "晚上"
            } else {
                hourName = "夜晚"
            }
            var dayName = {
                '-2': '前天',
                '-1': '昨天',
                '0': '今天',
                '1': '明天',
                '2': '后天',
            }

            function zeroPoint(dc) {//传入时间戳，返回凌晨时间，用来两个时间相减后计算dayName
                var d = new Date(dc);
                d.setHours(0);
                d.setMinutes(0);
                d.setSeconds(0);
                //时间戳是毫秒级的，所以也需要把时间秒后面的多出来的毫秒给归零
                d = d - d % 1000;
                return d;
            }

            // var dates = Math.abs(Math.floor(((now - time))/(1000*60*60*24)));
            //当前时间减去需要计算的时间。向下四舍五入
            var dates = Math.floor((zeroPoint(time) - zeroPoint(now)) / (1000 * 60 * 60 * 24));

            var dN;
            dN = dayName[dates] || time.format('MM月DD日');
            return {
                day: dN,
                hour: hourName
            }
        },
        rendering: function (str, obj) {
            if (!obj) {
                return str;
            }
            var html = '', str = str;
            for (var i in obj) {
                var rex = new RegExp('{{' + i + '}}', 'g');
                str = str.replace(rex, obj[i] || '');
            }
            return str;
        }
    }
    window.yueajax = yun.ajax;
})(window, appid, 'fffa2a879e62e198924a95dc150dc33823bd0bf7abd3a20fff605f297ae9333804699723a6219048')

